<script module="drag" lang="wxs">
	var windowWidth = 0;
	var windowHeight = 0;
	var startX = 0;
	var startY = 0;
	var lastLeft = 0;
	var lastTop = 0;

	function init(data) {
		windowWidth = data.windowWidth;
		windowHeight = data.windowHeight;
		lastLeft = data.x;
		lastTop = data.y;
		return '';
	}

	function touchstart(event, ins) {
		var touch = event.touches[0] || event.changedTouches[0];
		startX = touch.pageX;
		startY = touch.pageY;
	}

	function touchmove(event, ins) {
		var D = ins.selectComponent('.drag');
		var info = JSON.parse(D.getDataset().info);

		var touch = event.touches[0] || event.changedTouches[0];
		var pageX = touch.pageX;
		var pageY = touch.pageY;
		var left = pageX - startX + (lastLeft || info.x);
		var top = pageY - startY + (lastTop || info.y);
		var w = D.getBoundingClientRect ? D.getBoundingClientRect().width : info.w;
		var h = D.getBoundingClientRect ? D.getBoundingClientRect().height : info.h;

		startX = pageX;
		startY = pageY;

		if (left <= 0) left = 0;
		if (top <= 0) top = 0;

		var _w = (windowWidth || info.windowWidth) - w;
		var _h = (windowHeight || info.windowHeight) - h;

		if (left >= _w) left = _w;
		if (top >= _h) top = _h;

		lastLeft = left;
		lastTop = top;

		D.setStyle({
			left: left + 'px',
			top: top + 'px'
		});
		
		// #ifndef MP-WEIXIN
		event.stopPropagation();
		event.preventDefault();
		// #endif
		
		return false;
	}
	module.exports = {
		touchstart: touchstart,
		touchmove: touchmove,
		init: init,
	}
</script>

<template>
	<!-- App兼容性：drag 包含在 view.drag-box -->
	<view class="drag-box">
		<view class="drag" :data-info="info" @touchstart="drag.touchstart" @touchmove="drag.touchmove"
			:style="{
				left: x + 'px',
				top: y + 'px',
				position: 'absolute',
				zIndex: 10000,
			}">
			{{ drag.init({ ...systemInfo, x, y }) }}
			<slot></slot>
		</view>
	</view>
</template>

<script>
	export default {
		name: "comDragBox",
		props: {
			x: {
				type: Number,
				default: () => 0,
			},
			y: {
				type: Number,
				default: () => 0,
			},
		},
		data() {
			const systemInfo = uni.getSystemInfoSync()
			return {
				info: "",
				systemInfo,
			};
		},
		mounted() {
			const query = uni.createSelectorQuery().in(this);
			query.select('.drag').boundingClientRect(data => {
				let info = {};

				info.w = data.width;
				info.h = data.height;
				
				info.windowWidth = this.systemInfo.windowWidth;
				info.windowHeight = this.systemInfo.windowHeight;
				
				info.x = this.x;
				info.y = this.y;
				
				this.info = JSON.stringify(info);
			}).exec();
		},
	}
</script>